package com.woniuxy.project115.kaer.tenant.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.project115.kaer.commons.util.SMSUtil;
import com.woniuxy.project115.kaer.tenant.config.WebSocketServer;
import com.woniuxy.project115.kaer.tenant.entity.OrderLog;
import com.woniuxy.project115.kaer.tenant.entity.ServiceOrder;
import com.woniuxy.project115.kaer.tenant.mapper.OrderLogMapper;
import com.woniuxy.project115.kaer.tenant.mapper.ServiceOrderMapper;
import com.woniuxy.project115.kaer.tenant.service.ServiceOrderService;
import com.woniuxy.project115.kaer.tenant.service.TenantStoreService;
import com.woniuxy.project115.kaer.tenant.util.Data;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class XxlJobHandler {

    @Resource
    private TenantStoreService tenantStoreService;

    @Resource
    private ServiceOrderMapper serviceOrderMapper;

    @Resource
    private OrderLogMapper orderLogMapper;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private ServiceOrderService serviceOrderService;

    /**
     * @description: 定时任务 每日0点更新商家评分
     */
    @XxlJob("updateTenantStoreScoresJobHandler")
    public void updateTenantStoreScores() {
        tenantStoreService.updateScores();
    }

    /**
     * @description: 每日9点 18点提醒用户未支付订单
     */
    @XxlJob("remindPayOrderJobHandler")
    public void remindPayOrder() throws Exception {
        List<ServiceOrder> list = serviceOrderMapper.selectList(
                new QueryWrapper<ServiceOrder>().eq("state", Data.SERVICE_ORDER_WAIT_PAYMENT)
        );
        for (ServiceOrder serviceOrder : list) {
            //websocket通知
            WebSocketServer.sendInfo("您的订单号为" + serviceOrder.getServiceOrderNum() + "的服务订单尚时未支付，请及时支付。", serviceOrder.getUserId() + "");
            //发送短信提醒
            SMSUtil.sendCode(serviceOrder.getUserPhone(), "[卡尔养车]您的订单号为" + serviceOrder.getServiceOrderNum() + "的服务订单尚时未支付，请及时支付。");
        }
    }

    /**
     * @description: 订单服务完成后，用户超过24小时未验收，系统自动验收
     */
    @XxlJob("autoCheckOrderJobHandler")
    public void autoCheckOrder() throws Exception {
        // 调用api，获取参数
        String serviceOrderNum = XxlJobHelper.getJobParam();
        RLock lock = redissonClient.getFairLock(serviceOrderNum);
        try {
            lock.lock();
            ServiceOrder serviceOrder = serviceOrderMapper.selectById(serviceOrderNum);
            if (serviceOrder == null) {
                throw new Exception("订单不存在");
            }
            if (serviceOrder.getState() == Data.SERVICE_ORDER_COMPLETED || serviceOrder.getState() == Data.SERVICE_ORDER_WAIT_EVALUATE || serviceOrder.getState() == Data.SERVICE_ORDER_WAIT_PAYMENT) {
                throw new Exception("订单已验收，请勿重复操作");
            }
            if (serviceOrder.getState() != Data.SERVICE_ORDER_WAIT_CHECK) {
                throw new Exception("服务尚未完成，无法验收");
            }

            //更改订单状态
            if (serviceOrder.getPayState() == Data.PAY_STATE_PAYED) {// 用户已经支付过了
                serviceOrder.setState(Data.SERVICE_ORDER_WAIT_EVALUATE);
                serviceOrderMapper.updateById(serviceOrder);

            } else {// 用户还未支付
                serviceOrder.setState(Data.SERVICE_ORDER_WAIT_PAYMENT);
                serviceOrderMapper.updateById(serviceOrder);
            }

            // websocket 通知用户
            WebSocketServer.sendInfo("您的订单号为" + serviceOrderNum + "的服务订单在服务完成24小时后未验收，系统已自动验收。", serviceOrder.getUserId() + "");

            // 更新订单日志
            orderLogMapper.insert(
                    new OrderLog()
                            .setOperator("系统")
                            .setServiceOrderNum(serviceOrderNum)
                            .setOperateTime(LocalDateTime.now())
                            .setOperateType("超时自动验收")
            );

        } finally {
            lock.unlock();
        }
    }

    @XxlJob("getSalesDataJobHandler")
    public void getSalesData() throws Exception {
        //统计每天24小时内服务销售数据
        serviceOrderService.generateDailySalesData();
    }
}